package lv.premia.katalogs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
//import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import lv.premia.katalogs.DatabaseManager;
import lv.premia.katalogs.ItemList;
import lv.premia.katalogs.JSONParser;

public class AddItemListActivity extends Activity {
    private EditText edit;
    private ItemList itemList;
	//protected String price;
    
  //JSON get content
	
	
	 // Creating JSON Parser object
   JSONParser jParser = new JSONParser();

   ArrayList<HashMap<String, String>> productsList;

   // url to get all products list
   private static String url_all_products = "http://91.190.43.115/android_clone/get_all_products.php";

   // JSON Node names
   private static final String TAG_SUCCESS = "success";
   private static final String TAG_PRODUCTS = "products";
  	//Product Table Column names
	private static final String TAG_PID = "pid";
	
	private static final String TAG_NAME = "name";
	private static final String TAG_PRICE = "price";
	private static final String TAG_DESCRIPTION = "description";
	private static final String TAG_CREATED_AT = "created_at";
   
   // products JSONArray
   JSONArray products = null;
	
	
	//

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ViewGroup contentView = (ViewGroup) getLayoutInflater().inflate(R.layout.add_item_list, null);
        edit = (EditText) contentView.findViewById(R.id.edit);

        Button btn = (Button) contentView.findViewById(R.id.button_save);
        setupButton(btn);
        
        setupItemList();
        setContentView(contentView);
    }

	private void setupItemList() {
		// TODO Auto-generated method stub
		 Bundle bundle = getIntent().getExtras();
	        if (null!=bundle && bundle.containsKey(Constants.keyItemListId)) {
	            int itemListId = bundle.getInt(Constants.keyItemListId);
	            itemList = DatabaseManager.getInstance().getItemListWithId(itemListId);
	           // itemList = DatabaseManager.getInstance().getAllItemLists(itemListId);
	            edit.setText(itemList.getName());
	        }
		
	}

    private void setupButton(Button btn) {
        final Activity activity = this;
        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	//OnClick droping and recreating tables
            	DatabaseManager.getInstance().resetTables(itemList);
              
                            	
            	
            String name2 = edit.getText().toString();
              String price2 = edit.getText().toString();
               
                
                if (null!=name2 && name2.length()>0) {
                
                	if (null!=itemList) {
                  //     updateItemList(name);
                    	
                    } else {
                    	 //JSON
                    	List<NameValuePair> params = new ArrayList<NameValuePair>();
                        // getting JSON string from URL
                                  
                        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
                    	
                    	//JSON
                    	try{
                            	    // Checking for SUCCESS TAG
                                    int success = json.getInt(TAG_SUCCESS);
                     
                                    if (success == 1) {
                                    	
                                       	// products found
                                        // Getting Array of Products
                                    	
                                    	
                                    	products = json.getJSONArray(TAG_PRODUCTS);
                           
                                    	//int i = 0;
                                    	//while (i < products.length()) {
                                    	for (int i = 0; i < products.length(); i++) {
                                                JSONObject c = products.getJSONObject(i);
                                                
                                                String pid = c.getString(TAG_PID);
                                               String name = c.getString(TAG_NAME);
                                               String price = c.getString(TAG_PRICE);
                                                String description = c.getString(TAG_DESCRIPTION);
                                                String created_at = c.getString(TAG_CREATED_AT);
                                              
                                                createNewItemList(pid, name, price, description, created_at);    
                                              
                                    	}
                                    	 
                                    	
                                    	
                                	}
                                    //
                                	}catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                	/*Json try*/
                    	
                    	
                        //createNewItemList(name, price);
                           
                    }
                
                    finish();
                } else {
                    new AlertDialog.Builder(activity)
                    .setTitle("Error")
                    .setMessage("Invalid name!")
                    .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .show();
                }
            }
        });
        
     }
    




	private void updateItemList(String name) {
        if (null!=itemList) {
            itemList.setName(name);
            DatabaseManager.getInstance().updateItemList(itemList);
        }
    }


	private void createNewItemList(String pid, String name, String price, String description, String created_at) {
		ItemList l = new ItemList();
		l.setPid(pid);
		l.setName(name);
		l.setPrice(price);
		l.setDescription(description);
		l.setCreatedAt(created_at);
		DatabaseManager.getInstance().addItemList(l);
	}
	


}